import React, { useState } from "react";
import { Link, Outlet } from "react-router-dom";
import "./index.scss";
import * as api from "api/index";
import classNames from "classnames";
import {useNavigate} from "react-router";
import { inject,observer} from "mobx-react";

function Login({store}) {
    const navigate = useNavigate();

    let [phone,setPhone] = useState('13688889999');
    let [code,setCode] = useState('');
    
    // 获取验证码
    const getCode = () => {
        api.$userGetSmsCode({phone}).then(res => {
            console.log(res);
            setCode(res.result.smsCode) 
        })
    }

    // 登录
    const login = () => {
        let obj = {
            phone,
            smsCode: code,
        }
        api.$userLoginBySmsCode(obj).then(res => {
            console.log(res);
            // 把 phone 和 token 存入 store
            store.updatePhone(phone);
            store.updateToken(res.result.token);
            console.log(res.result.token);
            navigate('/my'); 
        })
    }


  return (
    <div className="login-index">
      {/* 头部 */}
      <div className="top bg-fff flex aic jc-sb">
        <p><Link to="/my"><span className="iconfont icon-xiangzuo">返回</span></Link></p>
        <p>登录页面</p>
        <p></p>
      </div>

      {/* 登录 */}
      <div className="box mt-30 ml-30 bg-fff">
        <p>
          <input value={phone} onChange={(ev) => {setPhone(ev.target.value)}} name="phone" maxLength='11' placeholder="请输入手机号码" />
        </p>
        <p className="mt-10 mb-10">
          <input value={code} onChange={(ev) => {setCode(ev.target.value)}} name="code"  placeholder="请输入验证码" /> 
          <span onClick={getCode} className="ml-5">获取验证码</span>
        </p>
        <p className="btn flex jc-sa">
          <button className="cancel">取消</button> <button className={classNames("",{login:!!code})} onClick={login}>立即登录</button>
        </p>
      </div>
    </div>
  );
}

export default inject("store")(observer(Login));
 